package org.wpahs.ahn.rssfeed;

import java.util.Locale;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.IBinder;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


public class SettingsActivity extends ActionBarActivity
    implements OnFragmentInteractionListener{

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    ViewPager mViewPager;
    Menu mMenu;
    CurrentFeedsFragment mCurrentFeedsFragment;
    SyncSettingsFragment mSyncSettingsFragment;
    FindFeedFragment mFindFeedFragment;
    private RSSGetService mService;
    private Boolean mServiceBound = false;
    private void registerReceiver(){
        IntentFilter filter = new IntentFilter();
        filter.addAction(RSSGetService.NOTIFICATION);
        filter.addAction(RSSGetService.FEED_START);
        filter.addAction(RSSGetService.FEED_DONE);
        filter.addAction(RSSGetService.FEEDITEM_IMAGE_DONE);
        filter.addAction(RSSGetService.FEED_IMAGE_DONE);

        filter.addAction(getString(R.string.broadcast_removed_feed));
        filter.addAction(getString(R.string.broadcast_newfeed_added));

        registerReceiver(receiver, filter);
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            if(intent.getAction().equals(RSSGetService.FEED_DONE)){
                int feedId = intent.getIntExtra(getString(R.string.feed_id),0);
            }else if(intent.getAction().equals(RSSGetService.FEED_IMAGE_DONE)){
                int feedId=intent.getIntExtra(getString(R.string.feed_id), 0);

            } else if (intent.getAction().equals(context.getString(R.string.broadcast_removed_feed))){
                int feedId=intent.getIntExtra(getString(R.string.feed_id),0);
            }

        }
    };

    public void processFeed(int feedId){
        mService.process(feedId,true);
    }


    @Override
    protected void onStart() {
        super.onStart();
        // Bind to LocalService

        //re-bind the background service
        Intent intent = new Intent(this, RSSGetService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onResume() {
        //re-register the receiver.
        registerReceiver();
        super.onResume();
    }

    @Override
    protected void onPause() {
        //if our activity pauses it's proper to unregister the
        //broadcast receiver
        unregisterReceiver(receiver);
        super.onPause();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        setTitle(getString(R.string.title_section1));

        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //add,edit,sync
                switch (position){
                    case 0:
                        setTitle(getString(R.string.title_section1));
                        mMenu.getItem(0).setVisible(true);
                        mMenu.getItem(1).setVisible(false);
                        mMenu.getItem(2).setVisible(true);
                        break;
                    case 1:
                        setTitle(getString(R.string.title_section2));
                        mMenu.getItem(0).setVisible(true);
                        mMenu.getItem(1).setVisible(true);
                        mMenu.getItem(2).setVisible(false);
                        break;
                    default:
                        setTitle(getString(R.string.title_section3));
                        mMenu.getItem(0).setVisible(false);
                        mMenu.getItem(1).setVisible(true);
                        mMenu.getItem(2).setVisible(true);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_settings, menu);
        mMenu = menu;
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_addfeed) {
            mViewPager.setCurrentItem(2,true);
            return true;
        }else if (id == R.id.action_editfeeds) {
            mViewPager.setCurrentItem(0,true);
            return true;
        }else if (id == R.id.action_syncsettings) {
            mViewPager.setCurrentItem(1, true);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            if(position == 0){
                mCurrentFeedsFragment = CurrentFeedsFragment.newInstance();
                return mCurrentFeedsFragment;
            }else if(position==1){
                mSyncSettingsFragment = SyncSettingsFragment.newInstance();
                return mSyncSettingsFragment;
            }else{
                mFindFeedFragment = FindFeedFragment.newInstance();
                return mFindFeedFragment;
            }
        }

        @Override
        public int getCount() {
            // Show 2 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
                case 0:
                    return "a"; //getString(R.string.title_section1).toUpperCase(l);
                case 1:
                    return "b"; //getString(R.string.title_section2).toUpperCase(l);
            }

            return null;
        }
    }

    private ServiceConnection mConnection = new ServiceConnection(){

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            RSSGetService.LocalBinder binder = (RSSGetService.LocalBinder)service;
            mService = binder.getService();
            mServiceBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mServiceBound = false;
        }
    };


}
